<template>
  <!--临时工艺更改修改工艺-->
  <div class="temp_work_stage_edit">
    <process-template
      ref="processTemplate"
    ></process-template>
    <one-title title="编辑工艺-临时工艺更改" @refreshData="init">
      <div class="mes_btn">
        <el-button @click="returnPage">
          <i class="iconfont icon-btn_return"></i>
          返回列表
        </el-button>
        <el-button @click="save" type="success" v-if="!isEmpty&&!isLoading">
          <i class="iconfont icon-btn_Save"></i>
          保存工艺
        </el-button>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <empty-page v-if="isEmpty&&!isLoading"></empty-page>
      <div v-loading="isLoading" v-if="!isEmpty">
        <process
          :infoData="batchProcessDetail">
        </process>
        <work-stage-edit
          ref="workStageEdit"
          :materialName="batchProcessDetail.materialName || ''"
          :entry="'batch'"
          :workstageData="workstageData"
          :startIndex="finishedData.length + startedData.length + 1"
          @tempSave="init"
          @change="handleChange"
          @saveStage="handleSaveStage">
          <div class="stage_disable" v-if="finishedData.length + startedData.length !== 0">
            <div class="stage_disable_item" style="margin-bottom: 10px" v-if="finishedData.length !== 0">
              <span class="status_finished">已完工</span>
              <div
                :key="index"
                class="stage_line"
                v-for="(item, index) in finishedData"
              >
                <span @click="showDisDialog(item)" class="stage_name">工序{{index + 1}}：{{item.workstageName}} |</span>
                <span v-if="item.paramTemplateId" @click="openProcessTemplate(item, false)">模板</span>
                <span v-else @click="openProcessTemplate(item, true)" class="stage_operate">模板</span>
              </div>
            </div>
            <div class="stage_disable_item" v-if="startedData.length !== 0">
              <span class="status_started">已开工</span>
              <div
                :key="index"
                class="stage_line"
                v-for="(item, index) in startedData"
              >
                <span @click="showDisDialog(item)" class="stage_name">工序{{index + startedData.length + 1}}：{{item.workstageName}} |</span>
                <span v-if="item.paramTemplateId" @click="openProcessTemplate(item, false)">模板</span>
                <span v-else @click="openProcessTemplate(item, true)" class="stage_operate">模板</span>
              </div>
            </div>
          </div>
        </work-stage-edit>
      </div>
    </div>
    <stage-dialog
      ref="stageDialog"
      :workstageData="workstageData"
    ></stage-dialog>
  </div>
</template>

<script>
/* eslint-disable no-unused-vars */

import EmptyPage from '@/components/EmptyPage'
import StageDialog from '@/components/workStageEdit/StageDialog'
// 工艺详情
import {Process} from '../../../../components/process'
import {WorkStageEdit} from '../../../../components/workStageEdit'
import checkAssignRule from '../../../../validate/checkAssignRule'
import {ProcessTemplate} from '../../../../components/Template'

// 获取工艺接口
let editTechProcInterface = 'a/tmpturnoverbatch/tmpTurnoverBatch/editTechProc'
// 保存工艺接口
let saveTechProcInterface = 'a/tmpturnoverbatch/tmpTurnoverBatch/changeTechProc'
// store模块
let storeModule = 'temporaryWorkbench'

export default {
  name: 'TempWorkStageEdit',
  components: {
    EmptyPage,
    Process,
    WorkStageEdit,
    StageDialog,
    ProcessTemplate
  },
  data() {
    return {
      isLoading: false,
      isEmpty: false,
      startWatch: false,
    }
  },
  computed: {
    saveState() {
      return this.$store.state.saveState
    },
    // 批次工艺详情
    batchProcessDetail() {
      return this.$store.state[storeModule].tempTechProc.techProc || {}
    },
    // 可选工艺
    workstageData() {
      return this.$store.state[storeModule].workstageData.list || []
    },
    // 获取已开工工序
    startedData() {
      return this.$store.state[storeModule].tempTechProc.startedWorkstages || []
    },
    // 获取已完成工序
    finishedData() {
      return this.$store.state[storeModule].tempTechProc.finishAndStartWorkstages || []
    },
    // 获取可以编辑的工序（未开始）
    enableData() {
      return this.$store.state[storeModule].tempTechProc.toBeStartedWorkstages || []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    openProcessTemplate(item, isNew) {
      let obj = {
        // 物料名称
        materialName: this.batchProcessDetail.materialName || '',
        // 工序名称
        workstageName: item.workstageName,
        // 工序Id
        workstageId: item.id,
        // 批次类型
        entry: 'batch',
        // 是否新增
        isNew
      }
      this.$refs.processTemplate.openDialog(obj)
    },
    init() {
      this.startWatch = false
      this.isLoading = true
      Promise.all([this.getStageList(), this.getWorkStageList()])
        .finally(() => {
          this.isLoading = false
        })
    },
    // 打开不可编辑弹框
    showDisDialog(item) {
      this.$refs.stageDialog.openDisDialog(item)
    },
    // 工序序号补0操作
    handleChange(value) {
      value.map((item, index) => {
        let sort = index + this.finishedData.length + this.startedData.length + 1
        item.sort = sort < 10 ? ('0' + sort) : sort
      })
      this.$store.commit('SortTempWorkStageList', value)
    },
    getStageList() {
      this.isEmpty = false
      let postData = {
        method: 'post',
        url: editTechProcInterface,
        data: {
          turnoverId: this.$route.query.id
        },
        module: storeModule,
        state: 'tempTechProc'
      }
      return this.$store.dispatch('saveData', postData)
        .then((value) => {
          if (Object.keys(value).length === 0) {
            this.isEmpty = true
          }
          this.$refs.workStageEdit.initStageList(this.enableData)
          this.startWatch = true
        })
        .catch(() => {
          this.isEmpty = true
        })
    },
    handleSaveStage() {
      // 保存工艺不跳转
      this.save(false).then(() => {
        this.$refs.workStageEdit.hasStageChange = false
      })
    },
    // 保存工艺
    save(flag = true) {
      if (this.saveState === true) return
      if (!checkAssignRule(this.enableData)) return
      this.$store.commit('SetSaveState', true)
      let batchWorkstageList = [...this.finishedData, ...this.startedData, ...this.enableData]
      batchWorkstageList.map((item, index) => {
        let sort = index + 1
        item.sort = sort < 10 ? ('0' + sort) : sort
      })
      let commitObj = {
        method: 'post',
        url: saveTechProcInterface,
        data: {
          turnoverId: this.$route.query.id,
          batchWorkstageList,
          oldTurnoverBatch: this.$store.state[storeModule].tempTechProc.oldTurnoverBatch,
          oldBatchWorkstageList: this.$store.state[storeModule].tempTechProc.oldBatchWorkstageList,
        },
        noCommit: true
      }
      return this.$store.dispatch('saveData', commitObj)
        .then(() => {
          this.saveSuccess(flag)
        })
        .catch(() => {
          this.$store.commit('SetSaveState', false)
        })
    },
    saveSuccess(flag = true) {
      this.$message.success({
        message: '保存成功',
        duration: 500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false) // 保存成功时需要将页面变化标记重置回false
          if (!flag) {
            this.$store.commit('SetSaveState', false)
            this.init()
            return
          }
          this.$store.dispatch('delCurrentViews', this.$route).then(() => {
            this.$store.commit('SetSaveState', false)
            this.$router.push('/temporaryWorkbench')
            this.$store.commit('SetRefresh', true)
          })
        }
      })
    },
    // 返回列表
    returnPage() {
      this.$router.push('/temporaryWorkbench')
    },
    // 获取可选工序列表
    getWorkStageList() {
      let commitObj = {
        method: 'post',
        url: 'a/workstagerepository/workstageRepository/list',
        module: storeModule,
        state: 'workstageData',
        data: {
          'pageSize': 10000,
          'pageNo': 1
        }
      }
      return this.$store.dispatch('saveData', commitObj)
    },
  },
  watch: {
    enableData: {
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        } else {
          this.$store.commit('SetHasDetailChange', false)
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
  .temp_work_stage_edit {
    // 不可编辑工序
    .stage_disable {
      margin: 20px;
      padding: 20px 0;
      border-bottom: 1px solid #ced5dd;
      font-size: 14px;

      span {
        display: inline-block;
      }

      .status_finished, .status_started {
        width: 48px;
        height: 22px;
        line-height: 21px;
        text-align: center;
        border-radius: 2px;
        font-size: 12px;
      }

      .status_finished {
        background-color: @mesProcedureCompleted;
      }

      .status_started {
        background-color: @mesProcedureAlready;
      }

      .stage_line {
        font-size: 14px;
        display: inline-block;
        margin-right: 18px;
        color: #0066cc;
        cursor: pointer;

        .stage_operate {
          text-decoration: underline;
        }
      }
    }
  }
</style>
